package 链表.单向.练习;
//找出并返回两个单链表相交的起始节点
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Text_7 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        //求各自的长度
        int lenA = 0;
        int lenB = 0;
        ListNode curA = headA;
        ListNode curB = headB;
        while(curA!=null){
            lenA++;
            curA = curA.next;
        }
        while(curB!=null){
            lenB++;
            curB = curB.next;
        }
        //重新指向
         curA = headA;
         curB = headB;
        //长的先走
        int len;
        if(lenA>lenB){
            len = lenA-lenB;
            while (len>0){
                curA = curA.next;
                len--;
            }
        }else {
            len = lenB-lenA;
            while (len>0){
                curB = curB.next;
                len--;
            }
        }
        //找相遇的点
        while (curA!=null){
            if(curA == curB){
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }
        return null;
    }
}
